package com.cloudxingkong.dianyinke.Student.Ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.Adapter.MyAppointmentAdapter;
import com.cloudxingkong.dianyinke.Student.bean.MyAppointmentEntity;
import com.cloudxingkong.dianyinke.Uri.studentUri.StudentUri;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * @我的预约Activity
 * @name:Zxrui
 */
public class MyAppointment extends BaseActivity implements MyAppointmentAdapter.onTouchItemPositions, SwipeRefreshLayout.OnRefreshListener {
    private ListView lv_myAppointment;
    private List<MyAppointmentEntity.ListBean> list;
    private MyAppointmentAdapter myAppointmentAdapter;
    private SharedPreferences sharedPreferences;
    private int mPosition;
    private String sessionID;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        super.onCreateView(savedInstanceState);
        setContentView(R.layout.activity_my_appointment);
        init();

        lv_myAppointment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent entity = new Intent(MyAppointment.this, MyAppointmentDetail.class);
                entity.putExtra("pic", list.get(position).getAvatar() + "");//老师头像
                entity.putExtra("memname", list.get(position).getMemname() + ""); //老师名字
                entity.putExtra("title", list.get(position).getTitle() + "");//标题
                entity.putExtra("label", list.get(position).getLabel() + "");//标签
                entity.putExtra("content", list.get(position).getNote() + "");//内容
                entity.putExtra("time", list.get(position).getTime() + "");//时间
                entity.putExtra("workepc", list.get(position).getWorkepc() + "");//教师简绍
                entity.putExtra("note", list.get(position).getNote() + "");//课程安排
                entity.putExtra("addr", list.get(position).getAddr() + "");//上课地点
                entity.putExtra("isuse", list.get(position).getIsuse() + "");//使用状态

                int lessonid = list.get(position).getLessonid();
                int teacherid = list.get(position).getTeacherid();
                entity.putExtra("teacherID", teacherid + "");//老师ID
                entity.putExtra("lessonID", lessonid + "");//课程id

                entity.putExtra("id", list.get(position).getId() + "");//课程id
                int price = list.get(position).getPrice();
                entity.putExtra("price", price + "");
                startActivity(entity);
            }
        });
    }

    private void loadData() {
        swipeRefreshLayout.setRefreshing(true);
        final String upLoadUrl = ThisUri.SERVER_YUMING + StudentUri.MYAPPOINTMENT;
        RequestParams params = new RequestParams(upLoadUrl);
        params.addHeader("cookie", sessionID);
        params.addBodyParameter("ispayed", "1");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("test", "我的预约：" + result);
                if (result != null && !result.equals("")) {
                    Message msg = handler.obtainMessage();
                    msg.what = 1;
                    msg.obj = result;
                    handler.sendMessage(msg);
                    swipeRefreshLayout.setRefreshing(false);
                } else {
                    Toast.makeText(getApplication(), "您还没有任何预约哦！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                handler.sendEmptyMessage(2);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void init() {
        sharedPreferences = MyAppointment.this.getSharedPreferences("data_dyk", 0);
        lv_myAppointment = ((ListView) findViewById(R.id.lv_myAppointment));
        list = new ArrayList<>();
        myAppointmentAdapter = new MyAppointmentAdapter(list, this, this);
        sessionID = CookieHelper.getSessionID(sharedPreferences);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.myAppointment_swiperefresn);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(this);
        //设置自动刷新
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        });
        loadData();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String state = (String) msg.obj;
                    if (state != null) {
                        Gson gson = new Gson();
                        MyAppointmentEntity myAppointmentEntity = gson.fromJson(state, MyAppointmentEntity.class);
                        list.addAll(myAppointmentEntity.getList());
                        swipeRefreshLayout.setRefreshing(false);
                        //创建设配器

                        lv_myAppointment.setAdapter(myAppointmentAdapter);
                        myAppointmentAdapter.notifyDataSetChanged();
                        //   swipeRefreshLayout.setRefreshing(false);
                        break;
                    } else {
                        Toast.makeText(getApplication(), "我的预约获取失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2:
                    swipeRefreshLayout.setRefreshing(false);
                    Toast.makeText(getApplication(), "获取失败请查看网络...", Toast.LENGTH_SHORT).show();
            }
        }
    };

    //返回按钮
    public void back(View view) {
        finish();
    }

    @Override
    public void onTouch(int position) {
        mPosition = position;
    }

    @Override
    public void onUse(int id, final TextView btn, final TextView text) {
        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + StudentUri.POSITIVE_USE_LESSON);
        params.addHeader("cookie", sessionID);
        params.addBodyParameter("id", list.get(mPosition).getLessonid() + "");//Todo  空值
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                boolean isUse = false;
                Log.e("test", "确认使用 " + result);
                Object success = LoginJsonUtils.getJsonFromLogin(result).get("success");
                isUse = (boolean) success;
                if (isUse) {
                    btn.setVisibility(View.GONE);
                    text.setVisibility(View.VISIBLE);
                    swipeRefreshLayout.setRefreshing(false);
                } else {
                    swipeRefreshLayout.setRefreshing(false);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    @Override
    public void onRefresh() {
        list.clear();
        loadData();
    }
}
